import React, { useEffect, useRef, useState } from "react";
import Header from "./Header";
import Main from "./Main";
import Footer from "./Footer";
import "./ToDoList.css";
import PubSub from "pubsub-js";

export default function ToDoListPubsub() {
  let [todoList, setTodoList] = useState([
    { id: 1, title: "吃饭", done: false },
    { id: 2, title: "睡觉", done: false },
    { id: 3, title: "打游戏", done: false },
  ]);

  let refFlag = useRef(true);

  let chooseAll = (e) => {
    setTodoList((todoList) => {
      return todoList.map((item) => {
        return { ...item, done: e.target.checked };
      });
    });
  };

  let clearAll = () => {
    setTodoList((todoList) => {
      return todoList.filter((item) => !item.done);
    });
  };

  useEffect(() => {
    //componentDidUpdate
    if (refFlag.current) {
      refFlag.current = false;
      return;
    }
    localStorage.setItem("todoList", JSON.stringify(todoList));
  }, [todoList]);

  useEffect(() => {
    //componentDidMount+componentDidUpdate
    let todoList = JSON.parse(localStorage.getItem("todoList")) || [];
    setTodoList(todoList);

    let addTodoId = PubSub.subscribe("addItem", (msg, title) => {
      setTodoList((todos) => {
        return [...todos, { id: Math.random(), title, done: false }];
      });
    });
    let deleteTodoId = PubSub.subscribe("deleteItem", (msg, id) => {
      setTodoList((todoList) => {
        return todoList.filter((item) => item.id !== id);
      });
    });
    let chooseItem = PubSub.subscribe("chooseItem", (msg, id) => {
      setTodoList((todoList) => {
        return todoList.map((item) => {
          if (item.id === id) {
            return { ...item, done: !item.done };
          } else {
            return item;
          }
        });
      });
    });
    return () => {
      PubSub.unsubscribe(addTodoId);
      PubSub.unsubscribe(deleteTodoId);
      PubSub.unsubscribe(chooseItem);
    };
  }, []);

  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <Main todoList={todoList}></Main>
        <Footer
          todoList={todoList}
          clearAll={clearAll}
          chooseAll={chooseAll}
        ></Footer>
      </div>
    </div>
  );
}
